package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
     public Result handleException(Exception e) {
        log.error("服务器发生异常：{}", e);
        return  Result.error("出错啦，请连续管理员");
    }
    @ExceptionHandler
    public  Result handleDuplicateKeyException(DuplicateKeyException  e) {
         log.error("服务器发生异常：{}", e);
        String  message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg =  message.substring(i);
        String[] arr =  errMsg.split(" ");
         return  Result.error( arr[2] + "已存在");
    }

    @ExceptionHandler(ClazzHasStudentException.class)
    public ResponseEntity<String> handleClazzHasStudentException(ClazzHasStudentException ex) {
        // 返回错误提示
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(ex.getMessage());
    }
     @ExceptionHandler(DeptHasEmpException.class)
     public ResponseEntity<String> handleDeptHasEmpException(DeptHasEmpException ex) {
        // 返回错误提示
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(ex.getMessage());
    }
}
